package longrise.phone.com.bjjt_henan.lunchandlogin;

import android.content.Context;
import android.text.TextUtils;
import android.text.method.PasswordTransformationMethod;
import android.text.method.TransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.FormParameter;
import com.longrise.android.LFView;
import com.longrise.bjjt.BaseApplication;
import com.longrise.bjjt.util.EnCryptDeCrypt;
import com.longrise.bjjt.util.StringUtils;
import com.longrise.bjjt.util.UiUtil;

import longrise.phone.com.bjjt_henan.R;
import longrise.phone.com.bjjt_henan.Utils.ApiImpI;
import longrise.phone.com.bjjt_henan.Utils.BDLocationManager;
import longrise.phone.com.bjjt_henan.Utils.CodeCountHelper;
import longrise.phone.com.bjjt_henan.Utils.CommontUtils;
import longrise.phone.com.bjjt_henan.Utils.DialogUtils;
import longrise.phone.com.bjjt_henan.Utils.VerifityHelper;

/**
 * 注册界面
 */
public class RegisterView extends LFView implements View.OnClickListener {
    private Context context = null;
    private View view = null;
    private Button bt_regiseter;
    private EditText et_regiseter_text5;
    private EditText et_regiseter_text4;
    private EditText et_regiseter_text3;
    private EditText et_regiseter_text2;
    private EditText et_regiseter_text1;
    private TextView codeTV;
    private BaseApplication baseApplication;
    private LinearLayout pwdLayout;
    private LinearLayout cpwdLayout;

    private VerifityHelper codeHelper;

    private BDLocationManager manager;

    private String longitude;

    private String latitude;

    private CodeCountHelper helper;

    public RegisterView(Context c) {
        super(c);
        this.context = c;
    }

    @Override
    public void refreshByTime() {

    }

    @Override
    public FormParameter getFormParameter() {
        FormParameter fp = new FormParameter();
        fp.setShowtitle(false);
        return fp;
    }

    @Override
    public void refresh() {
        codeHelper.loadPicCode();
        manager.startLocation();
    }

    @Override
    public View getView() {
        return view;
    }

    @Override
    public void init() {
        initView();
        regEvent(true);
        baseApplication = (BaseApplication) context.getApplicationContext();
    }

    private void initView() {
        view = View.inflate(context, R.layout.view_register, null);
        et_regiseter_text1 = (EditText) view.findViewById(R.id.et_regiseter_text1);
        et_regiseter_text2 = (EditText) view.findViewById(R.id.et_regiseter_text2);
        et_regiseter_text3 = (EditText) view.findViewById(R.id.et_regiseter_text3);
        et_regiseter_text4 = (EditText) view.findViewById(R.id.et_regiseter_text4);
        et_regiseter_text5 = (EditText) view.findViewById(R.id.et_regiseter_text5);
        bt_regiseter = (Button) view.findViewById(R.id.bt_regiseter);
        codeTV = (TextView) view.findViewById(R.id.register_tv_getcode);
        pwdLayout = (LinearLayout) view.findViewById(R.id.login_layout_pwd);
        cpwdLayout = (LinearLayout) view.findViewById(R.id.login_layout_cpwd);

        if (null == codeHelper) {
            codeHelper = new VerifityHelper(view, context);
        }
        if (null == manager) {
            manager = new BDLocationManager(context);
            manager.setLocationListener(listener);
        }

        //标题栏
        TextView titleTV = (TextView) view.findViewById(R.id.tv_title);
        titleTV.setText(R.string.user_register);
        view.findViewById(R.id.hn_btn_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OnDestroy();
                closeForm();
            }
        });

        et_regiseter_text4.setTransformationMethod(PasswordTransformationMethod.getInstance());
        et_regiseter_text5.setTransformationMethod(PasswordTransformationMethod.getInstance());
    }

    private void regEvent(boolean b) {
        if (null != bt_regiseter) {
            bt_regiseter.setOnClickListener(b ? this : null);
        }
        if (null != codeTV) {
            codeTV.setOnClickListener(b ? this : null);
        }
        if (null != pwdLayout) {
            pwdLayout.setOnClickListener(b ? this : null);
        }
        if (null != cpwdLayout) {
            cpwdLayout.setOnClickListener(b ? this : null);
        }
    }

    @Override
    public void onClick(View v) {
        try {
            switch (v.getId()) {
                case R.id.bt_regiseter:
                    if (ifEdittextNull()) {//判断几个输入框是否为空
                        register();
                    }
                    break;
                case R.id.register_tv_getcode://获取验证码
                    getCode();
                    break;
                case R.id.login_layout_pwd:
                    CommontUtils.setSeePwd(et_regiseter_text4);
                    setShowDrawable(et_regiseter_text4, (ImageView) view.findViewById(R.id.login_iv_mpwd));
                    break;
                case R.id.login_layout_cpwd:
                    CommontUtils.setSeePwd(et_regiseter_text5);
                    setShowDrawable(et_regiseter_text5, (ImageView) view.findViewById(R.id.login_iv_cpwd));
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //设置明文密码时的图像标识
    private void setShowDrawable(EditText editText, ImageView imageView) {
        TransformationMethod method = editText.getTransformationMethod();
        if (method instanceof PasswordTransformationMethod) {
            imageView.setImageResource(R.mipmap.eye);
        } else {
            imageView.setImageResource(R.mipmap.eye_select);
        }
    }

    /**
     * 注册
     */
    public void register() {
        try {
            final String username = et_regiseter_text1.getText().toString().trim();
            String phone = et_regiseter_text2.getText().toString().trim();
            String code = et_regiseter_text3.getText().toString().trim();
            String pwd = et_regiseter_text4.getText().toString().trim();
            if (TextUtils.isEmpty(longitude)) {
                longitude = baseApplication.getLongitude();
            }
            if (TextUtils.isEmpty(latitude)) {
                latitude = baseApplication.getLatitude();
            }
            DialogUtils.showDialog(context);
            final String depwd = EnCryptDeCrypt.getInstance().EnCrypt(pwd);//加密
            ApiImpI.getInstance(baseApplication).register(username, depwd, phone, code, longitude, latitude,
                    new ApiImpI.RequestCallBack() {
                        @Override
                        public void onError(String error) {
                            DialogUtils.closeDialog();
                            if (!TextUtils.isEmpty(error)) {
                                UiUtil.showToast(getContext(), error);
                            }
                        }

                        @Override
                        public void onSuccess(Object result) {
                            DialogUtils.closeDialog();
                            EntityBean bean = (EntityBean) result;
                            String redes = bean.getString("redes");
                            Toast.makeText(context, redes, Toast.LENGTH_SHORT).show();
                            String restate = bean.getString("restate");
                            if (TextUtils.equals("1", restate)) {//注册成功
//                                EntityBean dataBean = bean.getBean("data");
//                                //缓存数据
//                                baseApplication.setToken(dataBean.getString("token"));
//                                baseApplication.setKckpName(username);
//                                baseApplication.setKckpPass(depwd);
                                //返回到登录界面
                                OnDestroy();
                                closeForm();
                            }
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取验证码
     */
    public void getCode() {
        if (!codeHelper.checkPicCode()) {
            return;
        }
        String phone = et_regiseter_text2.getText().toString().trim();
        if (!StringUtils.isPhone(phone)) {
            Toast.makeText(context, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        String imgCode = codeHelper.getImgCode();
        String imageId = codeHelper.getPicBean().getString("imgid");
        DialogUtils.showDialog(context);
        ApiImpI.getInstance(baseApplication).getValidCode(phone, imgCode, imageId,
                new ApiImpI.RequestCallBack() {
                    @Override
                    public void onError(String error) {
                        DialogUtils.closeDialog();
                    }

                    @Override
                    public void onSuccess(Object result) {
                        DialogUtils.closeDialog();
                        EntityBean bean = (EntityBean) result;
                        String redes = bean.getString("redes");
                        if (!TextUtils.isEmpty(redes)) {
                            UiUtil.showToast(getContext(), redes);
                        }
                        String restate = bean.getString("restate");
                        if (TextUtils.equals(restate, "1")) {
                            if (null == view) {
                                return;
                            }
                            if (null == helper) {
                                helper = new CodeCountHelper(codeTV);
                            }
                            helper.startCount();
                        }
                    }
                });
    }

    /**
     * 判断输入框是否为空
     *
     * @return
     */
    private boolean ifEdittextNull() {
        String et_regiseter_text1content = et_regiseter_text1.getText().toString().trim();
        String et_regiseter_text2content = et_regiseter_text2.getText().toString().trim();
        String et_regiseter_text3content = et_regiseter_text3.getText().toString().trim();
        String et_regiseter_text4content = et_regiseter_text4.getText().toString().trim();
        String et_regiseter_text5content = et_regiseter_text5.getText().toString().trim();
        if (!CommontUtils.isAccount(et_regiseter_text1content)) {
            UiUtil.showToast(context, "用户名要求由6-10位字母和数字组成");
            return false;
        }
        if (!codeHelper.checkPicCode()) {
            return false;
        }
        if (TextUtils.isEmpty(et_regiseter_text2content)) {
            UiUtil.showToast(context, "手机号为空");
            return false;
        } else if (TextUtils.isEmpty(et_regiseter_text3content)) {
            UiUtil.showToast(context, "短信验证码为空");
            return false;
        } else if (!CommontUtils.isPassword(et_regiseter_text4content)) {
            UiUtil.showToast(context, "请输入6~15位由字母和数字组合的密码！");
            return false;
        }
//        else if (TextUtils.isEmpty(et_regiseter_text5content)) {
//            UiUtil.showToast(context, "确认密码为空");
//            return false;
//        }
//        if (!TextUtils.equals(et_regiseter_text4content, et_regiseter_text5content)) {
//            UiUtil.showToast(context, "两次输入的密码不一致!");
//            return false;
//        }
        return true;
    }

    @Override
    public void OnDestroy() {
        super.OnDestroy();
        view = null;
        regEvent(false);
        if (null != helper) {
            helper.destroy();
            helper = null;
        }
        codeHelper = null;
        manager = null;
    }

    private BDLocationListener listener = new BDLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            if (bdLocation != null) {
                longitude = String.valueOf(bdLocation.getLongitude());
                latitude = String.valueOf(bdLocation.getLatitude());
            }
            // 停止定位
            manager.ondestroty();
        }
    };
}
